<!DOCTYPE html>
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" />
<title>FogCloud</title>
<link href="//api.easylink.io/bower_components/ionic/css/ionic.min.css" rel="stylesheet">
<script src="//api.easylink.io/bower_components/ionic/js/ionic.bundle.min.js"></script>
<script type="text/javascript">
    function getParameterByName(name) {
        var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
        return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
    }
    var access_token = getParameterByName('access_token');
    var device_list = [];
    
    var deviceLists = getParameterByName('device_list');
    if ( deviceLists !== null ){
        try {
            deviceLists = JSON.parse(deviceLists);
            
            for ( var i in deviceLists ) {
                var device = deviceLists[i];
                if ( device[0] === null ) continue;
                var product_id = device[0].split('/')[0];
                var alias = device[3] ? device[3] : device[0];
                device_list.push({'alias': alias, 'device_id': device[0], 'product_id': product_id, 'time': new Date(parseInt(device[1])*1000).toLocaleString(), 'state': device[2]});
            }
        } catch(e) {
            alert(e);
        }
    }

    angular.module('ionicApp', ['ionic'])

    .controller('MyCtrl', function($scope, $ionicPopup, $ionicListDelegate, $http) {
      $scope.items = device_list;
      $scope.access_token = access_token;
        
      $scope.data = {
        showDelete: false
      };
      $scope.listCanSwipe = true;
      $scope.showPopup = function(item) {
          var index = $scope.items.indexOf(item);
          $scope.data = {}

          // An elaborate, custom popup
          var myPopup = $ionicPopup.show({
            template: '<input type="text" ng-model="data.alias">',
            title: '',
            subTitle: '修改名称',
            scope: $scope,
            buttons: [
              { text: 'Cancel' },
              {
                text: '<b>Save</b>',
                type: 'button-positive',
                onTap: function(e) {
                  if (!$scope.data.alias) {
                    e.preventDefault();
                  } else {
                    $http.post(
                        'http://api.easylink.io/v1/device/modify',
                        {
                            device_id : item.device_id,
                            alias     : $scope.data.alias
                        }, {
                            headers : {
                                'AUTHORIZATION' : "token " + access_token
                            }
                        } 
                    ).success(function(data) {
                        $scope.items[index].alias = $scope.data.alias;
                        $ionicListDelegate.closeOptionButtons();

                    }).error(function(data){
                        alert(data.error.message);
                        return; 
                    });  
                      
                    
                  }
                }
              }
            ]
          });
         };
      
      $scope.reloadPage = function() {
    	  $http.post(
 		        'http://api.easylink.io/v1/device/devices',
 		       null,{
 		            headers : {
 		                'AUTHORIZATION' : "token " + access_token
 		            }
 		        }
 		    ).success(function(data) {
 		    	$scope.items = [];
 		    	for ( var i in data ) {
 	                var device = data[i];
 	                if ( device === null ) continue;
                    var product_id = device.id.split('/')[0];
 	                var alias = device.alias ? device.alias : device.id;
 	                $scope.items.push({'alias': alias, 'device_id': device.id, 'product_id': product_id, 'time': device.created, 'state': device.online});
 	            }
 		    	
 		    	
 		    }).error(function(data) {
 	        	alert(data.error.message);
 	        	return;
 	        });
      };
    });
    </script>
</head>
<body ng-controller="MyCtrl">
    
    <ion-header-bar class="bar-positive">

      <h1 class="title">我的设备</h1>
	  <div class="buttons">
        <button class="button ion-refresh" ng-click="reloadPage()"></button>
      </div>
    </ion-header-bar>
    <ion-content>
      
      <ion-list can-swipe="listCanSwipe"  show-delete="data.showDelete" show-reorder="data.showReorder">

        <ion-item ng-repeat="item in items" 
                  item="item"
                  href="{{ item.product_id }}.html?device_id={{ item.device_id }}&access_token={{ access_token }}&alias={{ item.alias }}" class="item-remove-animate">
          
          <i ng-if="item.state==1" class="icon ion-record positive" ></i><i ng-if="item.state==0" class="icon ion-record assertive" ></i> {{ item.alias }}<br>
          <span class="item-note">ID : {{ item.device_id }}</span>
         
         <ion-option-button class="button-assertive"
                           ng-click="showPopup(item)">
            Edit
          </ion-option-button>

        </ion-item>

      </ion-list>

    </ion-content>
    

</body>
</html>
